package com.mankind.ssm.controller;

import com.mankind.ssm.common.CONSTANT;
import com.mankind.ssm.common.Page;
import com.mankind.ssm.common.util;
import com.mankind.ssm.pojo.Role;
import com.mankind.ssm.pojo.User;
import com.mankind.ssm.pojo.UserInfo;
import com.mankind.ssm.pojo.UserRole;
import com.mankind.ssm.service.RoleService;
import com.mankind.ssm.service.UserInfoService;
import com.mankind.ssm.service.UserRoleService;
import com.mankind.ssm.service.UserService;
import com.sun.org.apache.xpath.internal.SourceTree;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Mankind on 2017/7/10.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    //service类
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;
    /**
     * 查找所用用户控制器方法
     * @return
     * @throws Exception
     */
    @RequestMapping("/findUser")
    public ModelAndView findUser()throws Exception{
        ModelAndView modelAndView = new ModelAndView();

        //调用service方法得到用户列表
        User user = userService.findUser();
        //将得到的用户列表内容添加到ModelAndView中
        List<User> users=new ArrayList<User>();
        users.add(user);
        modelAndView.addObject("users",users);
        //设置响应的jsp视图
        modelAndView.setViewName("findUser");
        return modelAndView;
    }
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, User user){
        ModelAndView modelAndView = new ModelAndView();
        System.out.println(user.getUserAccount()+" "+user.getUserPassword());
        //方法绑定绑定参数
        Integer userId=userService.loginCheck(user);
        //如果验证失败,返回登录失败页面
        System.out.println("登录验证ID："+userId);
        if(userId==null){
            modelAndView.setViewName("loginError");
        }
        //如果验证通过,进入个人主页
        else{
            //进入主页前验证身份
           boolean check= userRoleService.managerCheck(userId);
           //管理员身份验证通过
           if(check==true){
               modelAndView.setViewName("manager");
           }else{
               modelAndView.setViewName("home");
           }
            HttpSession session=request.getSession();
            session.setAttribute("userId",userId);
        }
        return modelAndView;
    }
    @RequestMapping("/register")
    public ModelAndView register(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        String userAccount=request.getParameter("userAccount");
        String userPassword=request.getParameter("userPassword");
        String userName=request.getParameter("userName");
        System.out.println(userAccount+" "+userPassword+ " " +userName);
        User user=new User(userAccount,userPassword);
        Integer userId=userService.register(user);
        System.out.println("注册用户ID:"+userId);
        //返回userId表明注册成功
        if(userId!=null){
            System.out.println("注册成功!!!");
            modelAndView.setViewName("userInfo");
            HttpSession session=request.getSession();
            session.setAttribute("userId",userId);
            request.setAttribute("userName",userName);
        }else{
            System.out.println("注册失败!!!");
            modelAndView.setViewName("userError");
        }
       return modelAndView;
    }
    @ResponseBody
    @RequestMapping(value="/accountCheck",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map AccountExistCheck(HttpServletRequest request){
        Map<String,Object> json=new HashMap<String, Object>();
        String account=request.getParameter("userAccount");
        System.out.println(account);
        boolean isExist=userService.existJudge(account);
        //如果存在则说明不能被注册,如果不存在才能注册
        json.put("valid",!isExist);
        System.out.println(!isExist+"检测完毕!!");
        return json;
    }
    @RequestMapping("/register_detail")
    public ModelAndView reigster_detail(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        HttpSession session=request.getSession();
        Integer userId=(Integer)session.getAttribute("userId");
        String IP= util.getRealIP(request);
        String userName=request.getParameter("userName");
        //if(userName==null) userName="";
        String sex=request.getParameter("sex");
        //if(sex==null) sex="";
        String userBirthday=request.getParameter("userBirthday");
        //if(userBirthday==null) userBirthday="";
        String job=request.getParameter("job");
        //if(job==null) job="";
        String email=request.getParameter("email");
        //if(email==null)email="";
        String wechat=request.getParameter("wechat");
       // if(wechat==null)email="";
        String telephone=request.getParameter("telephone");
        Date date = null;
        //if(telephone==null)telephone="";
       if(userBirthday!=null||userBirthday!=""){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                if(userBirthday!=null){
                    date = sdf.parse(userBirthday);
                    System.out.println(date);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        UserInfo userInfo=new UserInfo();
        userInfo.setRecentlyTime(new Date());
        userInfo.setUserBirthday(date);
        userInfo.setUserId(userId);
        userInfo.setCurrentIp(IP);
        userInfo.setEmail(email);
        userInfo.setJob(job);
        userInfo.setSex(sex);
        userInfo.setTelephone(telephone);
        userInfo.setUserName(userName);
        userInfo.setWechat(wechat);
        System.out.println(userInfo);
        userService.registerDetail(userInfo);
        modelAndView.setViewName("home");
        return modelAndView;
    }
    @ResponseBody
    @RequestMapping(value="/getUserInfoByPage",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map getUserInfoByPage(HttpServletRequest request){
        Map<String,Object> json=new HashMap<String, Object>();
        Integer currentPage=Integer.parseInt(request.getParameter("Page"));
        Integer userId=(Integer)request.getSession().getAttribute("userId");
        Page<UserInfo> page=userInfoService.getUserInfoByPage(CONSTANT.USERINFO_LIST_SIZE,currentPage);
        for(int i=0;i<page.getObj().size();i++){
            Date date= page.getObj().get(i).getRecentlyTime();
        }

        json.put("userInfoList",page.getObj());
        return json;
    }
    @ResponseBody
    @RequestMapping(value="/getUserInfoTotalPages",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map getUserInfoTotalPages(HttpServletRequest request){
        Map<String,Object> json=new HashMap<String, Object>();
        Integer totalPages=userInfoService.getTotalNumber();
        json.put("totalPages",totalPages);
        System.out.println(totalPages);
        return json;
    }
    @ResponseBody
    @RequestMapping(value="/getUserInfoAndRoleByPage",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map getUserInfoAndRoleByPage(HttpServletRequest request){
        Map<String,Object> json=new HashMap<String, Object>();
        Integer currentPage=Integer.parseInt(request.getParameter("Page"));
        Page<UserInfo> page=userInfoService.getUserInfoByPage(CONSTANT.USERINFO_LIST_SIZE,currentPage);
        int size=page.getObj().size();
        List<List<Role>> listOfList=new ArrayList<List<Role>>();
        List<Role> allRole=roleService.selectAllRole();
        for(int i=0;i<size;i++){
            Integer id=page.getObj().get(i).getUserId();
            listOfList.add(userRoleService.getRoleById(id));
        }
        json.put("userInfoList",page.getObj());
        json.put("roleListOfUser",listOfList);
        json.put("allRole",allRole);
        return json;
    }
    @ResponseBody
    @RequestMapping(value="/updateUserInfo",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void updateUserInfo(HttpServletRequest request){
        Integer id=Integer.parseInt(request.getParameter("id"));
        String userName=request.getParameter("userName");
        String telephone=request.getParameter("telephone");
        String wechat=request.getParameter("wechat");
        String email=request.getParameter("email");
        UserInfo userInfo=userInfoService.getUserInfoById(id);
        userInfo.setUserId(id);
        userInfo.setUserName(userName);
        userInfo.setTelephone(telephone);
        userInfo.setWechat(wechat);
        userInfo.setEmail(email);
        userInfoService.update(userInfo);
    }
    @ResponseBody
    @RequestMapping(value="/deleteUserInfo",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void deleteUser(HttpServletRequest request){
        Integer id=Integer.parseInt(request.getParameter("id"));
        System.out.println("准备删除id:"+id);
        userService.deleteById(id);
    }
    @ResponseBody
    @RequestMapping(value="/roleAssign",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public void roleAssign(HttpServletRequest request){
        Integer id=Integer.parseInt(request.getParameter("id"));
        System.out.println("分配id:"+id);
        String[] roleName =request.getParameterValues("roleName");
        userRoleService.assignRole(id,roleName);
    }
    @ResponseBody
    @RequestMapping(value="/loadUserInfo",method= RequestMethod.POST,produces="application/json;charset=UTF-8")
    public Map loadUserInfo(HttpServletRequest request){
        Map<String,Object> json=new HashMap<String, Object>();
        Integer id=(Integer)request.getSession().getAttribute("userId");
        UserInfo userInfo=userInfoService.getUserInfoById(id);
        json.put("userInfo",userInfo);
        return json;
    }
}